package com.atguigu.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

@Service
public class PaymentService {
    //正常访问(一定没问题的方法)
    public String paymentInfo_OK(Integer id){
        return "*******************正常方法调用了*******************"+id;
    }
    //超时的方法
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
            //设定最大超时时间为1s,超过了就出错
    })
    //如果本方法出事了，paymentInfo_TimeOutHandler方法来兜底
    public String paymentInfo_TimeOut(Integer id){
//        int age=10/0;
        try {
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "*******************超时方法调用了(耗时3s)*******************"+id;
    }
    public String paymentInfo_TimeOutHandler(Integer id){
        return "paymentInfo_TimeOutHandler方法提醒您超时或运行报错了┭┮﹏┭┮";
    }
    /*==================服务熔断====================*/
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
            //请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "60000"),
            //服务熔断的时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),
            //失败率达到多少百分比跳闸
    /*这里指的是在窗口期60s内如果10次内有6次及以上请求失败时触发服务熔断,此时服务将被熔断，
    就算是正常的服务也不能正确响应，只有这60s的时间窗口期过后才会恢复调用链路，之后再次进入下一个窗口期
     */})
    public String paymentCircuitBreaker(@PathVariable("id") Integer id){
        if(id < 0){
            throw new RuntimeException("******id不能负数");//抛一个“不能负数”异常
        }
        String serialNumber = IdUtil.simpleUUID();
        /*IdUtil.simpleUUID()等于UUID.randomUUID().toString()
         HUtool工具包的方法：生成的是不带-的字符串*/
        return Thread.currentThread().getName()+"\t"+"调用成功，流水号: " + serialNumber;
    }
    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id){
        return "id 不能负数，请稍后再试，/(ㄒoㄒ)/~~   id: " +id;
    }
}
